const Router = require("koa-router");
const pool = require("../database.js");
const crypto = require("crypto");
const { anthVertify } = require("../common/middleware.js");
const fs = require("fs");
const path = require("path");
const jwt = require("jsonwebtoken");
const errorTypes = require("../app/error-types");

const router = new Router({
  prefix: "/login",
});
router.get("/", async (ctx, next) => {
  try {
    const { name, password } = ctx.request.query;
    if (!name || !password) {
      const error = new Error(errorTypes.NAME_OR_PASSWORD_IS_REQUIRED);
      return ctx.app.emit("error", error, ctx);
    }
    const md5 = crypto.createHash("md5");
    let md5Pas = md5.update(password).digest("hex");
    const statement = `SELECT * FROM ${`user`} WHERE userName = ?;`;
    let [result] = await pool.execute(statement, [name]);
    if (result.length != 0 && result[0].password != md5Pas) {
      const error = new Error(errorTypes.PASSWORD_IS_INCORRENT);
      return ctx.app.emit("error", error, ctx);
    }
    if (result.length == 0) {
      const statement = `INSERT INTO  ${`user`} ( ${`userName`}, ${`password`}, ${`avatar`}) VALUES (?,?,?)`;
      let [data] = await pool.execute(statement, [
        name,
        md5Pas,
        "https://x0.ifengimg.com/ucms/2022_10/8A28619D49C8DE5999F84E9101E304F4F9DA73E1_size127_w1008_h435.jpg",
      ]);
    result = [{ id: data.insertId }];
    }
    let PRIVATE_KEY = fs.readFileSync(
      path.resolve(__dirname, "../common/private.key")
    );
    const token = jwt.sign({ id: result[0].id }, PRIVATE_KEY, {
      expiresIn: 60 * 60 * 24,
      algorithm: "RS256",
    });
    return ctx.body = {
      flag: true,
      data: { token: token, name: name, avatar:"https://x0.ifengimg.com/ucms/2022_10/8A28619D49C8DE5999F84E9101E304F4F9DA73E1_size127_w1008_h435.jpg" },
    };
  } catch (error) {
    console.log(error);
  }
});
router.post("/", anthVertify);
module.exports = router;
